<?php

class Controller_Page extends Controller_Site {
    public function action_show() {
        $page = ORM::factory('page', $this->request->param('id'));
        $this->content->set('page', $page);
    }
    
    public function action_edit() {
        $page = ORM::factory('page', $this->request->param('id'));
        $form = $this->getForm(URL::site('page/edit/' . $page->id));
        $form->set('page', $page);
        if($this->request->method() == "POST") {
            try {
                $page->title = $this->request->post('title');
                $page->content = $this->request->post('content');
                $page->save();

                $this->setFlash('notice', 'Sikeresen módosítottad az oldalt!');
                $this->request->redirect(URL::site('page/show/' . $page->id));
            }
            catch (ORM_Validation_Exception $e) {
                $form->set('errors', $e->errors('models'));
            }
        }
        
        $this->content->set('form', $form);
    }
    
    public function action_new() {
        $form = $this->getForm(URL::site('page/new'));
        
        if($this->request->method() == "POST") {
            try {
                $page = new Model_Page();
                $page->title = $this->request->post('title');
                $page->content = $this->request->post('content');
                $page->save();

                $this->setFlash('notice', 'Sikeresen felvetted az új oldalt!');
                $this->request->redirect(URL::site('page/show/' . $page->id));
            }
            catch (ORM_Validation_Exception $e) {
                $form->set('page', $page);
                $form->set('errors', $e->errors('models'));
            }
        }
        
        $this->content->set('form', $form);
    }
    
    function getForm($action) {
        $form = View::factory('page/form')->set('action', $action);
        
        $ckeditor = new CKEditor();
        $config = array("toolbar" =>
        array(
                    array(
        'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink', '-', 'Table'
                    )
                )
                );
        
                $form->set('ckeditor', $ckeditor);
        $form->set('config', $config);
        
        return $form;
    }
    
    public function action_list() {
        $pages = ORM::factory('page')->order_by('title')->find_all();
        $this->setVar('pages', $pages);
    }
    
    public function action_delete() {
        $page = new Model_Page($this->request->param('id'));
        try {
            $page->delete();
            $this->setFlash('notice', 'Sikeresen törölted az oldalt!');
            $this->request->redirect(URL::site('page/list'));
        }
        catch(Kohana_Exception $e) {
            $this->setFlash('error', $e->getMessage());
        }
    }
}